package com.kotlin.library.common

import android.app.Activity
import android.app.ActivityManager
import android.content.Context
import java.util.*

/**
 *
 * USER: zjw
 * DATA: 2018/11/30 0030
 * TIME: 上午 10:44
 * app Activity 管理 入栈,出栈,获取栈顶Activity,情况栈 ,退出app
 * 一个单利类
 */
class AppManager private constructor() {

    private val stackActivity: Stack<Activity> = Stack()

    companion object {
        val instance: AppManager by lazy { AppManager() }
    }

    /**
     * 入栈
     */
    fun addActivity(activity: Activity) {
        stackActivity.add(activity)
    }

    /**
     * 出栈
     */
    fun finishActivity(activity: Activity) {
        activity.finish()
        stackActivity.remove(activity)
    }

    /**
     * 获取栈顶元素
     */
    fun currentActivity(): Activity {
        return stackActivity.lastElement()
    }

    /**
     * 清空栈
     */
    fun finishAllActivity() {
        for (activity in stackActivity) {
            activity.finish()
        }
        stackActivity.clear()
    }

    /**
     * 退出app
     */
    fun exitApp(context: Context) {
        finishAllActivity()
        var activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        activityManager.killBackgroundProcesses(context.packageName)
        System.exit(0)
    }
}